package com.czy.owner.ui.packagecardproject;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.czy.owner.R;
import com.czy.owner.adapter.StorePackageDetailAdapter;
import com.czy.owner.api.OwnerPacMyInfoApi;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.MyPackageCardProjectDetailModel;
import com.czy.owner.entity.MyServicePackageItemList;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.DecimalUtil;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.utils.TimeUtils;
import com.czy.owner.utils.glide.GlideUtils;
import com.czy.owner.widget.FullyLinearLayoutManager;
import com.czy.owner.widget.MyRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by wangyang on 2016/12/15 0015.
 * 我的套餐详细
 */
public class MyPackageCardDetailActivity extends BaseActivity /*implements MyScrollView.ScrollViewLine*/ {
    //@ViewInject(R.id.myscrollview)
//    private MyScrollView myScrollView;
//    @ViewInject(R.id.line_headview)
//    private LinearLayout lineHeadView;
    @BindView(R.id.img_package_card_bg)
    ImageView imgPackageCardBg;
    @BindView(R.id.tv_package_card_name)
    TextView tvPackageCardName;
    @BindView(R.id.tv_now_price)
    TextView tvNowPrice;
    @BindView(R.id.tv_used_time)
    TextView tvUserTime;
    @BindView(R.id.tv_old_price)
    TextView tvOldPrice;
    @BindView(R.id.relative_bug_package)
    RelativeLayout relativeBugPackage;
    @BindView(R.id.tv_package_note)
    TextView tvPackageNote;


    //商品
    @BindView(R.id.ll_goods)
    LinearLayout llGoods;
    @BindView(R.id.rv_package_detail_goods)
    MyRecyclerView rvPackageDetailGoods;
    @BindView(R.id.tv_package_goods_head_title)
    TextView tvPackageGoodsHeadTitle;
    @BindView(R.id.tv_package_goods_head_money)
    TextView tvPackageGoodsHeadMoney;
    //服务
    @BindView(R.id.ll_service)
    LinearLayout llService;
    @BindView(R.id.rv_package_detail_service)
    MyRecyclerView rvPackageDetailService;
    @BindView(R.id.tv_package_service_head_title)
    TextView tvPackageServiceHeadTitle;
    @BindView(R.id.tv_package_service_head_money)
    TextView tvPackageServiceHeadMoney;
    @BindView(R.id.tv_give_amount)
    TextView tvGiveAmount;
    @BindView(R.id.tv_my_give_amount)
    TextView tvMyGiveAmount;
    @BindView(R.id.relat_goods_head)
    RelativeLayout relatGoodsHead;
    @BindView(R.id.relat_service_head)
    RelativeLayout relatServiceHead;

    private int userPackageId = 0;
    private double priceGood = 0.00;
    private double priceService = 0.00;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_package_card_detail;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        RxBus.getDefault().register(this);
        getToolbarTitle().setText(R.string.my_package_card_detail);
        getSubTitle().setText(R.string.my_package_card_punch_record);

        relativeBugPackage.setVisibility(View.GONE);
        userPackageId = getIntent().getIntExtra("userPackageId", 0);

        tvGiveAmount.setVisibility(View.INVISIBLE);

        getDataList();
    }

    @Override
    protected void updateViews() {

    }


    private void getDataList() {
        OwnerPacMyInfoApi ownerPacMyInfoApi = new OwnerPacMyInfoApi(new HttpOnNextListener<MyPackageCardProjectDetailModel>() {
            @Override
            public void onNext(MyPackageCardProjectDetailModel model) {
                setDataList(model);
            }

            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(MyPackageCardDetailActivity.this, e.getMessage());
            }
        }, this);
        ownerPacMyInfoApi.setSession(UserHelper.getInstance().getSessionInfoModel(MyPackageCardDetailActivity.this).getSession());
        ownerPacMyInfoApi.setStoreId(SharedPreferencesUtils.getParam(MyPackageCardDetailActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        ownerPacMyInfoApi.setUserPackageId(userPackageId + "");
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(ownerPacMyInfoApi);
    }


    private void setDataList(MyPackageCardProjectDetailModel model) {
        if (TextUtils.isEmpty(model.getLogo()) || model.getLogo().equals(" ")) {
            imgPackageCardBg.setVisibility(View.GONE);
        } else {
            GlideUtils.loadImage(MyPackageCardDetailActivity.this, model.getLogo(), imgPackageCardBg, new GlideUtils.ImageLoadListener<String, GlideDrawable>() {
                @Override
                public void onLoadingComplete(String uri, ImageView view, GlideDrawable resource) {

                }

                @Override
                public void onLoadingError(String source, Exception e) {

                }
            }, R.mipmap.default_banner, R.mipmap.default_banner);

        }
        if (model.getGiveAmount() > 0) {
            tvMyGiveAmount.setVisibility(View.VISIBLE);
            tvMyGiveAmount.setText("赠送余额: ¥" + DecimalUtil.formatNum(model.getGiveAmount() + ""));

        } else {
            tvMyGiveAmount.setVisibility(View.INVISIBLE);

        }
        tvPackageCardName.setText(model.getPackageName());
        String strNowPrice = "现价<font color='#ff5000'>" + "￥" + String.format("%.2f", model.getPrice()) + "</font>";
        tvNowPrice.setText(Html.fromHtml(strNowPrice));
        tvOldPrice.setText("原价￥" + String.format("%.2f", model.getOriginalPrice()));
        tvOldPrice.setPaintFlags(Paint. STRIKE_THRU_TEXT_FLAG|Paint.ANTI_ALIAS_FLAG);
        if(!TextUtils.isEmpty(model.getNote())){
            tvPackageNote.setVisibility(View.VISIBLE);
            tvPackageNote.setText(model.getNote());
        }else {
            tvPackageNote.setVisibility(View.GONE);
        }

        long startTime = model.getStartTime();
        long endTime = model.getEndTime();
        if (startTime == 0 || endTime == 0) {
            tvUserTime.setText("有效期: 永久有效");
        } else {
            tvUserTime.setText("有效期: " + TimeUtils.formatTimeDifference4(startTime) + "-" + TimeUtils.formatTimeDifference4(endTime));
        }


        List<MyServicePackageItemList> goodsList = new ArrayList<>();
        List<MyServicePackageItemList> serviceList = new ArrayList<>();


        for (int i = 0; i < model.getUserPackageItemList().size(); i++) {
            String itemName = model.getUserPackageItemList().get(i).getItemName();
            String specName = model.getUserPackageItemList().get(i).getSpecName();
            double price = model.getUserPackageItemList().get(i).getPrice();
            int count = model.getUserPackageItemList().get(i).getCount();
            String logo = model.getUserPackageItemList().get(i).getLogo();
            String status = model.getUserPackageItemList().get(i).getStatus();
            int totalCount = model.getUserPackageItemList().get(i).getTotalCount();
            boolean unlimitedCount = model.getUserPackageItemList().get(i).isUnlimitedCount();
            if (model.getUserPackageItemList().get(i).getItemType().equals("goods")) {
                goodsList.add(new MyServicePackageItemList(itemName, price, count, logo, status, totalCount, specName, unlimitedCount));
            } else if (model.getUserPackageItemList().get(i).getItemType().equals("service")) {
                serviceList.add(new MyServicePackageItemList(itemName, price, count, logo, status, totalCount, specName, unlimitedCount));
            }
        }


        if (goodsList != null && goodsList.size() > 0) {
            FullyLinearLayoutManager layoutManager = new FullyLinearLayoutManager(MyPackageCardDetailActivity.this);
            rvPackageDetailGoods.setLayoutManager(layoutManager);
            rvPackageDetailGoods.addItemDecoration(new RecycleViewDivider(MyPackageCardDetailActivity.this, LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));
            rvPackageDetailGoods.setAdapter(new StorePackageDetailAdapter(MyPackageCardDetailActivity.this, goodsList, true));
            for (int i = 0; i < goodsList.size(); i++) {
                priceGood = goodsList.get(i).getPrice() * goodsList.get(i).getCount() + priceGood;
            }
//            tvPackageGoodsHeadTitle.setText("商品项目" + "(" + goodsList.size() + "件" + ")");
            tvPackageGoodsHeadTitle.setText("商品项目");
//            tvPackageGoodsHeadMoney.setText("小计: ￥" + String.format("%.2f", priceGood));
            tvPackageGoodsHeadMoney.setText("");
        } else {
            llGoods.setVisibility(View.GONE);
        }


        if (serviceList != null && serviceList.size() > 0) {
            FullyLinearLayoutManager layoutManager = new FullyLinearLayoutManager(MyPackageCardDetailActivity.this);
            rvPackageDetailService.setLayoutManager(layoutManager);
            rvPackageDetailService.addItemDecoration(new RecycleViewDivider(MyPackageCardDetailActivity.this, LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));
            rvPackageDetailService.setAdapter(new StorePackageDetailAdapter(MyPackageCardDetailActivity.this, serviceList, true));

            for (int i = 0; i < serviceList.size(); i++) {
                priceService = serviceList.get(i).getPrice() * serviceList.get(i).getCount() + priceService;

            }
//            tvPackageServiceHeadTitle.setText("服务项目" + "(" + serviceList.size() + "件" + ")");
            tvPackageServiceHeadTitle.setText("服务项目");
//            tvPackageServiceHeadMoney.setText("小计: ￥" + String.format("%.2f", priceService));
            tvPackageServiceHeadMoney.setText("");
        } else {
            llService.setVisibility(View.GONE);
        }
    }

    //划卡记录
    @OnClick(R.id.toolbar_subtitle)
    public void punchRecord(View view) {
        Intent ti = new Intent(MyPackageCardDetailActivity.this, PunchRecordActivity.class);
        ti.putExtra("userPackageId", userPackageId);
        startActivity(ti);
    }


    @Subscribe(code = Constants.BUY_PACKAGE_SUCCESS_CODE, threadMode = ThreadMode.MAIN)
    public void eventBuyPackage(CommonEvent bugPackageEvent) {
        finish();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unRegister(this);

    }

    protected void setTitleLayout(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            int statusBarHeight = getStatusBarHeight(MyPackageCardDetailActivity.this.getBaseContext());
            view.setPadding(0, statusBarHeight, 0, 0);

        }
    }

    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen",
                "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

//    @Override
//    public void onScrollChanged(int l, int t, int oldl, int oldt) {
//        if (oldt < 10) {
//            lineHeadView.getBackground().setAlpha(0);
//        } else if (oldt < 40 && oldt > 10) {
//            lineHeadView.getBackground().setAlpha((int) (oldt / 8));
//        } else if (oldt < 70 && oldt > 40) {
//            lineHeadView.getBackground().setAlpha((int) (oldt / 7));
//        } else if (oldt < 100 && oldt > 70) {
//            lineHeadView.getBackground().setAlpha((int) (oldt / 6));
//        } else if (oldt < 130 && oldt > 100) {
//            lineHeadView.getBackground().setAlpha((int) (oldt / 5));
//        } else if (oldt < 150 && oldt > 130) {
//            lineHeadView.getBackground().setAlpha((int) (oldt / 4));
//        } else if (oldt < 180 && oldt > 150) {
//            lineHeadView.getBackground().setAlpha((int) (oldt / 3));
//        } else if (oldt < 200 && oldt > 180) {
//            lineHeadView.getBackground().setAlpha((int) (oldt / 2));
//        } else if (oldt >= 200) {
//            lineHeadView.getBackground().setAlpha(255);
//        }
//    }

}
